from rest_framework import viewsets
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import GenericViewSet

from utils.response import SuccessResponse
from utils.mixins import *


class ListAPIView(ListModelMixin,
                  GenericAPIView):
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class ReadOnlyModelViewSet(RetrieveModelMixin,
                           ListModelMixin,
                           GenericViewSet):
    """
    A viewset that provides default `list()` and `retrieve()` actions.
    """
    pass


class ModelViewSet(viewsets.ModelViewSet):
    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return SuccessResponse(data=res.data, msg='查询成功！')

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return SuccessResponse(data=res.data, msg='创建成功！')

    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()  # 逻辑删除

    def destroy(self, request, *args, **kwargs):

        instance = self.get_object()
        self.perform_destroy(instance)
        return SuccessResponse(data=None, msg='删除成功！')

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return SuccessResponse(data=res.data, msg='修改成功！')

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return SuccessResponse(data={'data': res.data}, msg='查询成功！')
